package cn.xspace.wnx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.base.PagerInfoView;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.HypyUtil;
import com.xspace.android.xafcommon.util.IntentConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.ServiceObjAdapter;
import cn.xspace.wnx.entity.ServiceObjBean;
import cn.xspace.wnx.view.QuickAlphabeticBar;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ServiceObjActivity extends BaseActivity {

    private static final String TAG = ServiceObjActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private ListView mListView;
    private TextView mTvSearch;
    private QuickAlphabeticBar mQuickSearch;
    private PagerInfoView mPagerView;

    private ArrayList<ServiceObjBean> mDataList;
    private ServiceObjAdapter mAdapter;
    private TextView mMsmCont;
    private RelativeLayout mRelativeSearch;
    private String user_id;
    private String plat_code;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(mContext);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_service_obj);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.my_service_obj_titleBar);
        mPagerView = (PagerInfoView) findViewById(R.id.service_obj_pager);
        mListView = (ListView) findViewById(R.id.lv_service_obj);
        mQuickSearch = (QuickAlphabeticBar) findViewById(R.id.quicksearch_service_obj_list);
        mTvSearch = (TextView) findViewById(R.id.edit_search);
        mTvSearch.setHint(getResources().getString(R.string.search));
        mMsmCont = (TextView) findViewById(R.id.msm_cont_fast_position_service_obj);
        mRelativeSearch = (RelativeLayout) findViewById(R.id.relative_search);
        mQuickSearch.init(mMsmCont);
        mQuickSearch.setListView(mListView);
        //mRelativeSearch=findViewById(R.id.)
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mQuickSearch.setHight(mQuickSearch.getHeight());
                mQuickSearch.setVisibility(View.VISIBLE);
            }
        }, 500);
    }

    @Override
    protected void initData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        plat_code = MyInfoUtil.getPlatCode();

        mDataList = new ArrayList<>();
        mAdapter = new ServiceObjAdapter(mContext, mDataList, mQuickSearch);
        mListView.setAdapter(mAdapter);
        requestNetWorkData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ServiceObjModifyActivity.class);
                startActivity(intent);
            }
        });
        mRelativeSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ServiceObjSearchActivity.class);
                startActivity(intent);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ServiceObjBean bean = mDataList.get(position);
                Intent intent = new Intent(ServiceObjActivity.this, MyUserInfoActivity.class);
                intent.putExtra(IntentConstant.friend_id, bean.user_id);
                intent.putExtra(IntentConstant.serviceobj_id, bean.serviceobj_id);
                startActivity(intent);
            }
        });
        mPagerView.setOnReloadClickListener(new PagerInfoView.OnReloadClickListener() {
            @Override
            public void onReloadClick(View v) {
                requestNetWorkData();
            }
        });
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        super.onEventMainThread(inParam);
        String type = inParam.get(EventBusConstant.TYPE).toString();
        if (EventBusConstant.SERVICE_OBJECT_ADD_SUCCESS.equals(type)) {
            requestNetWorkData();
            refreshList();
        } else if (EventBusConstant.SERVICE_OBJECT_STOP_SUCCESS.equals(type)) {
            String serviceObjId = inParam.get(EventBusConstant.ACTION_KEY).toString();
            Iterator<ServiceObjBean> iterator = mDataList.iterator();
            while (iterator.hasNext()) {
                ServiceObjBean bean = iterator.next();
                if (serviceObjId.equals(bean.serviceobj_id)) {
                    iterator.remove();
                    break;
                }
            }
            mAdapter.initAlpha(mDataList);
            refreshList();
        } else if (EventBusConstant.SERVICE_OBJECT_EDIT_SUCCESS.equals(type)) {
            ServiceObjBean editBean = (ServiceObjBean) inParam.get(EventBusConstant.ACTION_VALUE);
            for(int i = 0;i<mDataList.size();i++) {
                if (mDataList.get(i).serviceobj_id.equals(editBean.serviceobj_id)) {
                    mDataList.remove(i);
                    mDataList.add(i, editBean);
                }
            }
            mAdapter.initAlpha(mDataList);
            refreshList();
        }
    }

    private void refreshList() {
        mAdapter.notifyDataSetChanged();
    }

    private void requestNetWorkData() {
        showWaitDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("plat_code", plat_code);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_SERVICEOBJ, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<ServiceObjBean>>() {
                    @Override
                    public List<ServiceObjBean> call(BaseReturnBean baseReturnBean) {
                        List<ServiceObjBean> dataList;
                        Gson gson = new Gson();
                        dataList = gson.fromJson(baseReturnBean.data, new
                                TypeToken<List<ServiceObjBean>>() {
                                }.getType());
                        return dataList;
                    }
                })
                .doOnNext(new Action1<List<ServiceObjBean>>() {
                    @Override
                    public void call(List<ServiceObjBean> newList) {
                        if (newList.size() != 0) {
                            for (ServiceObjBean bean : newList) {
                                bean.shotKey = HypyUtil.cn2py(bean.user_name);
                            }
                            Collections.sort(newList, new Comparator<ServiceObjBean>() {
                                @Override
                                public int compare(ServiceObjBean lhs, ServiceObjBean rhs) {
                                    if (TextUtils.isEmpty(lhs.shotKey)) {
                                        return -1;
                                    }
                                    String key1 = lhs.shotKey.toUpperCase();
                                    Integer num1 = HypyUtil.chartSortMap.get(key1);
                                    String key2 = rhs.shotKey.toUpperCase();
                                    Integer num2 = HypyUtil.chartSortMap.get(key2);
                                    if (num1 == null) {
                                        return -1;
                                    }
                                    if (num2 == null) {
                                        return 1;
                                    }
                                    return num1.compareTo(num2);
                                }
                            });
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<ServiceObjBean>>() {
                    @Override
                    public void onCompleted() {
                        LogUtil.d(TAG, "onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        mPagerView.showNetWorkError();
                        e.printStackTrace();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(List<ServiceObjBean> newList) {
                        hideWaitDialog();
                        if (newList.size() > 0) {
                            mPagerView.hiddenPager();
                            mDataList.clear();
                            mDataList.addAll(newList);
                            mAdapter.initAlpha(mDataList);
                            refreshList();
                        } else {
                            mPagerView.showPageEmpty(R.string.service_obj_empty);
                        }
                    }
                });
    }
}

